/**
 * 
 */
package com.objectdraw.server;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;

import com.objectdraw.server.data.ResponseData;

/**
 * This class is responsible for opening up a socket on the host machine and
 * passing any service request to the Object Draw Server
 * 
 * @author Harrison
 */
public class CommunicationServer {

	public static void main(String args[]) {

		CommunicationServer cs = new CommunicationServer();
		cs.listen(5454);

	}

	/**
	 * Opens a Server Socket on the specified port and waits for connections.
	 * When a connection is accepted it is passed on to an ObjectDrawHandler for
	 * processing
	 * 
	 * @param port
	 *            number server should listen on
	 */
	protected void listen(int port) {
		try {
			ServerSocket listener = new ServerSocket(port);
			System.out.println("Object Draw Server running on port " + port);

			while (true) {
				Socket client = listener.accept();

				// Pass the client on to an Object Draw Handler
				new ObjectDrawHandler(client).start();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Broadcast a response to a set of clients
	 * 
	 * @param response
	 *            is the message you would like sent to the client
	 * @param to
	 *            is a socket connections to client
	 */
	public synchronized static void broadcast(ResponseData response, Socket to) {
		if (to != null && response != null) {
			if (!to.isClosed() && !to.isOutputShutdown()) {
				try {
					PrintWriter out = new PrintWriter(new OutputStreamWriter(to
							.getOutputStream()), true);
					out.println(response.toString());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * Broadcast a response to a set of clients
	 * 
	 * @param response
	 *            is the message you would like sent to the client
	 * @param to
	 *            is a list of socket connections to clients
	 */
	public synchronized static void broadcast(ResponseData response,
			List<Socket> to) {
		if (response != null) {
			for (Socket sock : to) {
				if (sock != null && !sock.isClosed()
						&& !sock.isOutputShutdown()) {
					try {
						PrintWriter out = new PrintWriter(
								new OutputStreamWriter(sock.getOutputStream()),
								true);
						out.println(response.toString());
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
}
